package com.jeeplus.test.postgraduate.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jeeplus.sys.service.OfficeService;
import com.jeeplus.test.jlnu.admissionInfo.domain.entity.AdmissionInfo;
import com.jeeplus.test.jlnu.admissionInfo.domain.entity.Supplement;
import com.jeeplus.test.jlnu.admissionInfo.domain.vo.AdmissionInfoDto;
import com.jeeplus.test.jlnu.admissionInfo.domain.vo.AdmissionInfoReqVo;
import com.jeeplus.test.jlnu.admissionInfo.domain.vo.AdmissionInfoRespVo;
import com.jeeplus.test.jlnu.admissionInfo.mapper.AdmissionInfoMapper;
import com.jeeplus.test.jlnu.admissionInfo.service.AdmissionInfoService;
import com.jeeplus.test.jlnu.student.domain.result.Node;
import com.jeeplus.test.postgraduate.domain.vo.PostgraduateReqVo;
import com.jeeplus.test.postgraduate.service.PostgraduateService;
import com.jeeplus.test.tools.resp.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "研究生信息")
@RestController
@Slf4j
@RequestMapping("/postgraduate")
public class PostgraduateController {


    @Autowired
    private PostgraduateService admissionInfoService;

    @Autowired
    private AdmissionInfoMapper admissionInfoMapper;

    @Autowired
    private OfficeService officeService;


    @ApiOperation("录取信息分页查询")
    @GetMapping("/page")
    public ResponseEntity<Page<Map<String, Object>>> getAdmissionInfoPage(PostgraduateReqVo admissionInfoReqVo,
                                                                          @RequestParam(defaultValue = "1") int pageNum,
                                                                          @RequestParam(defaultValue = "10") int pageSize) {
        Page<PostgraduateReqVo> page = new Page<>(pageNum, pageSize);
        Page<Map<String, Object>> pageResult = admissionInfoService.getAdmissionInfoPage(admissionInfoReqVo, page);

        // 确保 null 值字段被填充
        List<Map<String, Object>> modifiedRecords = pageResult.getRecords().stream()
                .map(record -> {
                    Map<String, Object> modifiedRecord = new HashMap<>();
                    record.forEach((key, value) -> modifiedRecord.put(key, value != null ? value : ""));
                    return modifiedRecord;
                })
                .collect(Collectors.toList());

        Page<Map<String, Object>> modifiedPage = new Page<>(pageResult.getCurrent(), pageResult.getSize(), pageResult.getTotal());
        modifiedPage.setRecords(modifiedRecords);

        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(modifiedPage);
    }

    @ApiOperation("批量审批接口")
    @PostMapping("/approval")
    public R approval(@RequestBody List<AdmissionInfo> admissionInfoRespVos) {

        admissionInfoService.approval(admissionInfoRespVos);
        return R.suc();
    }

    @ApiOperation("研究生数据修改接口")
    @PostMapping("/update")
    public R update(@RequestBody PostgraduateReqVo admissionInfoReqVo) {

        admissionInfoService.update(admissionInfoReqVo);
        return R.suc();
    }


    @ApiOperation("主表信息树")
    @PostMapping("admissionTree")
    public String buildDirectoryTree(PostgraduateReqVo admissionInfoReqVo) throws JsonProcessingException {

        if (org.apache.commons.lang.StringUtils.isNotEmpty(admissionInfoReqVo.getOfficeId())) {
            //获取机构下所有层级
            List<String> officesList = officeService.getOfficesTreeByParentId(admissionInfoReqVo.getOfficeId());
            officesList.add(admissionInfoReqVo.getOfficeId());
            admissionInfoReqVo.setOfficesList(officesList);
        }

        // 处理审批状态
        if (StringUtils.isNotEmpty(admissionInfoReqVo.getApproveState())) {
            String[] arr = admissionInfoReqVo.getApproveState().split(",");
            List<String> list = Arrays.asList(arr);
            admissionInfoReqVo.setApproveStateList(list);
        }

        // 处理type
        if (StringUtils.isNotEmpty(admissionInfoReqVo.getTypes())) {
            String[] arr = admissionInfoReqVo.getTypes().split(",");
            List<String> list = Arrays.asList(arr);
            admissionInfoReqVo.setTypeList(list);
        }

        Map<String, Map<String, List<String>>> tree = new LinkedHashMap<>();

        //判断是否是学生工作处
        if (StringUtils.isNotEmpty(admissionInfoReqVo.getTypes())
                && admissionInfoReqVo.getTypes().contains("4") && !admissionInfoReqVo.getTypes().contains("6")) {
            //是学生工作处
            admissionInfoReqVo.setTypeList(new ArrayList<>());
            String[] arr = admissionInfoReqVo.getTypes().split(",");
            admissionInfoReqVo.setFlag(arr[0]);//1,教务处，2在教育，3研究生
            admissionInfoReqVo.setTypes("4");

        } else {
            admissionInfoReqVo.setTypes("");
        }
        // 3. 根据院校ID执行查询
        List<AdmissionInfo> admissionInfos = admissionInfoMapper.selectAllByOfficeId(admissionInfoReqVo);

        for (AdmissionInfo row : admissionInfos) {
            // 检查 row 是否为 null，防止对 null 进行方法调用
            if (row == null) {
                continue; // 如果 row 为 null，则跳过这次循环
            }

            // 安全地获取各个字段，防止空指针异常
            String academy = row.getAdmissionAcademy();
            String major = row.getAdmissionMajor();
            String time = row.getAdmissionTime() != null ? row.getAdmissionTime().toString() : null;

            // 如果任何一个字段为 null，则不处理该条记录
            if (academy != null && major != null && time != null) {
                tree.computeIfAbsent(academy, k -> new LinkedHashMap<>())
                        .computeIfAbsent(major, k -> new ArrayList<>())
                        .add(time);
            }
        }

        // 假设convertToTargetFormat方法可以处理空数据并将数据转换为目标格式
        List<Node> formattedTree = convertToTargetFormat(tree);

        // 返回JSON字符串
        return new ObjectMapper().writeValueAsString(formattedTree);
    }

    private List<Node> convertToTargetFormat(Map<String, Map<String, List<String>>> data) {
        List<Node> result = new ArrayList<>();

        if (data == null || data.isEmpty()) {
            return result;
        }

        for (Map.Entry<String, Map<String, List<String>>> academyEntry : data.entrySet()) {
            String academyName = academyEntry.getKey();
            if (academyName == null || academyEntry.getValue() == null || academyEntry.getValue().isEmpty()) {
                continue;
            }

            Node academyNode = new Node(academyName);

            for (Map.Entry<String, List<String>> majorEntry : academyEntry.getValue().entrySet()) {
                String majorName = majorEntry.getKey();
                if (majorName == null || majorEntry.getValue() == null || majorEntry.getValue().isEmpty()) {
                    continue;
                }

                Node majorNode = new Node(majorName);

                for (String time : majorEntry.getValue()) {
                    if (time == null) {
                        continue;
                    }
                    Node timeNode = new Node(time);
                    majorNode.addChild(timeNode);
                }

                if (!majorNode.getChildren().isEmpty()) {
                    academyNode.addChild(majorNode);
                }
            }

            if (!academyNode.getChildren().isEmpty()) {
                result.add(academyNode);
            }
        }
        return result;
    }

}
